<template>
  <!-- 分类参数组件 -->
  <div class="cat-param">
    <!-- 头部路径导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容区 -->
    <el-card class="box-card">
      <el-alert
        :title="noticeConfig.text"
        :style="noticeConfig.style"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row style="margin-top: 15px">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            :options="categoryList"
            :props="casProps"
            ref="catCascader"
            popper-class="cat-cascader"
            @change="selectCasNode"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <el-row style="margin-top: 15px">
        <el-tabs type="border-card" @tab-click="tabsSWitch" value="manyAttr">
          <el-tab-pane label="动态参数" name="manyAttr">
            <el-row>
              <el-button
                type="primary"
                size="mini"
                :disabled="addParamsBtnDisabled"
                @click="dialogConfig.dialogAddParamVisible = true"
                >添加参数</el-button
              >
            </el-row>
            <el-row style="margin-top: 15px">
              <el-table
                :data="catParams"
                border
                row-key="index"
                stripe
                style="width: 100%"
              >
                <el-table-column label="" width="48" type="expand">
                  <template slot-scope="props">
                    <el-row>
                      <el-tag
                        :key="tag"
                        v-for="tag in props.row.attr_vals"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(props.row, tag)"
                      >
                        {{ tag }}
                      </el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="tagConfig.inputVisible"
                        v-model="tagConfig.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(props.row)"
                        @blur="handleInputConfirm(props.row)"
                      >
                      </el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showTagInput"
                        >+ New Tag</el-button
                      >
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="#" width="48" type="index">
                </el-table-column>
                <el-table-column prop="attr_name" label="参数名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="props">
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="editParam(props.row)"
                      >修改</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteParam(props.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="onlyAttr">
            <el-row>
              <el-button
                type="primary"
                size="mini"
                :disabled="addParamsBtnDisabled"
                @click="dialogConfig.dialogAddParamVisible = true"
                >添加属性</el-button
              >
            </el-row>
            <el-row style="margin-top: 15px">
              <el-table
                :data="catParams"
                border
                row-key="index"
                stripe
                style="width: 100%"
              >
                <el-table-column label="" width="48" type="expand">
                  <template slot-scope="props">
                    <el-row>
                      <el-tag
                        :key="tag"
                        v-for="tag in props.row.attr_vals"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(props.row, tag)"
                      >
                        {{ tag }}
                      </el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="tagConfig.inputVisible"
                        v-model="tagConfig.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(props.row)"
                        @blur="handleInputConfirm(props.row)"
                      >
                      </el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showTagInput"
                        >+ New Tag</el-button
                      >
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="#" width="48" type="index">
                </el-table-column>
                <el-table-column prop="attr_name" label="属性名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="props">
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="editParam(props.row)"
                      >修改</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteParam(props.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>

    <!-- 添加动态参数弹出层 -->
    <el-dialog
      :title="addParamForm.dialogTitle"
      :visible.sync="dialogConfig.dialogAddParamVisible"
      class="add-param-dialog"
      @closed="addParamForm.param = ''"
    >
      <el-form
        :model="addParamForm"
        :rules="editParamFormRules"
        ref="addParamForm"
        class="demo-ruleForm"
        :label-position="'left'"
        label-width="80px"
      >
        <el-form-item :label="addParamForm.dialogLabel" prop="param">
          <el-input v-model.trim="addParamForm.param"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogConfig.dialogAddParamVisible = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="addParamSubmit('addParamForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改参数弹出层 -->
    <el-dialog
      :title="editParamForm.dialogTitle"
      :visible.sync="dialogConfig.dialogEditParamVisible"
      class="edit-param-dialog"
      @closed="editParamForm.param = ''"
    >
      <el-form
        :model="editParamForm"
        :rules="editParamFormRules"
        ref="editParamForm"
        class="demo-ruleForm"
        :label-position="'left'"
        label-width="80px"
      >
        <el-form-item :label="editParamForm.dialogLabel" prop="param">
          <el-input v-model.trim="editParamForm.param"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogConfig.dialogEditParamVisible = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="editParamSubmit('editParamForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //加载层参数配置
      loadingConfig: {
        target: "body",
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
        text: "拼命加载中",
      },
      //头部消息提示条配置
      noticeConfig: {
        //文字
        text: "注意：只允许为第三级分类设置相关参数！",
        //样式
        style: {
          //字体颜色
          color: "#fff",
          //字体大小
          fontSize: "13px",
          //内容行高
          lineHeight: "21px",
          //背景颜色
          backgroundColor: "#E6A23C",
        },
      },
      //级联菜单属性
      casProps: {
        //触发方式
        expandTrigger: "hover",
        //父子节点是否为非关联
        checkStrictly: false,
        value: "cat_id",
        label: "cat_name",
      },
      //弹窗层配置
      dialogConfig: {
        //控制添加动态参数弹出层显示
        dialogAddParamVisible: false,
        //控制修改动态参数弹出层显示
        dialogEditParamVisible: false,
      },
      //标签配置
      tagConfig: {
        inputVisible: false,
        inputValue: "",
      },
      //分类列表数据
      categoryList: [],
      //参数列表
      catParams: [],
      //选中分类的ID
      selectCatId: null,
      //添加参数按钮是否禁用
      addParamsBtnDisabled: true,
      //添加参数表单数据
      addParamForm: {
        param: "",
        type: "many",
        dialogTitle: "添加动态参数",
        dialogLabel: "动态参数",
      },
      //修改参数表单数据
      editParamForm: {
        //正在编辑的参数名称
        param: "",
        //正在编辑参数的所属分类ID
        editCatId: null,
        //正在编辑的参数ID
        editParamId: null,
        //参数的属性值
        attrVals: [],
        type: "many",
        dialogTitle: "修改动态参数",
        dialogLabel: "动态参数",
      },
      //修改参数表单验证
      editParamFormRules: {
        param: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          {
            min: 1,
            max: 32,
            message: "参数名称在 1 到 32 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    tabsSWitch(tab) {
      //面板切换
      if (tab.paneName == "manyAttr") {
        this.manyAttrTabs();
      } else if (tab.paneName == "onlyAttr") {
        this.onlyAttrTabs();
      }
    },
    manyAttrTabs() {
      //切换到动态参数面板
      this.addParamForm.type = "many";
      this.addParamForm.dialogTitle = "添加动态参数";
      this.addParamForm.dialogLabel = "动态参数";
      this.editParamForm.type = "many";
      this.editParamForm.dialogTitle = "修改动态参数";
      this.editParamForm.dialogLabel = "动态参数";
      this.selectCasNode();
    },
    onlyAttrTabs() {
      //切换到静态属性面板
      this.addParamForm.type = "only";
      this.addParamForm.dialogTitle = "添加静态属性";
      this.addParamForm.dialogLabel = "静态属性";
      this.editParamForm.type = "only";
      this.editParamForm.dialogTitle = "修改静态属性";
      this.editParamForm.dialogLabel = "静态属性";
      this.selectCasNode();
    },
    getCategoryList() {
      //获取商品分类列表
      //发起请求
      this.$axios
        .get("/categories")
        .then((res) => {
          if (res.meta.status == 200) {
            //设置分类列表数据
            this.categoryList = res.data;
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    addParamSubmit(formName) {
      //添加参数
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开加载层
          var loading = this.$loading.service(this.loadingConfig);
          //发起请求
          this.$axios
            .post("/categories/" + this.selectCatId + "/attributes", {
              attr_name: this.addParamForm.param,
              attr_sel: this.addParamForm.type
            })
            .then((res) => {
              if (res.meta.status == 201) {
                //提示成功信息
                this.$message.success(res.meta.msg);
                //关闭弹出层
                this.dialogConfig.dialogAddParamVisible = false;
                //重新刷新数据
                this.getCatParams(this.addParamForm.type);
              } else {
                //提示错误信息
                this.$message.error(res.meta.msg);
              }
            })
            .catch((error) => {
              this.$message.error(error);
            })
            .finally(() => {
              //关闭加载层
              this.$nextTick(() => {
                loading.close();
              });
            });
        }
      });
    },
    editParam(obj) {
      //修改参数
      //设置正在修改的分类ID和属性ID
      this.editParamForm.editCatId = obj.cat_id;
      this.editParamForm.editParamId = obj.attr_id;
      this.editParamForm.param = obj.attr_name;
      //打开修改参数弹出层
      this.dialogConfig.dialogEditParamVisible = true;
    },
    editParamSubmit(formName) {
      //修改参数提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开加载层
          var loading = this.$loading.service(this.loadingConfig);
          //发起请求
          this.$axios
            .put(
              "/categories/" +
                this.editParamForm.editCatId +
                "/attributes/" +
                this.editParamForm.editParamId,
              {
                attr_name: this.editParamForm.param,
                attr_sel: this.editParamForm.type,
                attr_vals: this.editParamForm.attrVals.join(","),
              }
            )
            .then((res) => {
              if (res.meta.status == 200) {
                //提示成功信息
                this.$message.success(res.meta.msg);
                //关闭弹出层
                this.dialogConfig.dialogEditParamVisible = false;
                //重新刷新数据
                this.getCatParams(this.editParamForm.type);
              } else {
                //提示错误信息
                this.$message.error(res.meta.msg);
              }
            })
            .catch((error) => {
              this.$message.error(error);
            })
            .finally(() => {
              //关闭加载层
              this.$nextTick(() => {
                loading.close();
              });
            });
        }
      });
    },
    deleteParam(obj) {
      //删除参数
      //调用确认弹框
      this.$confirm("此操作将永久删除该参数，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //点击确定执行删除商品
        this.deleteParamSubmit(obj);
      });
    },
    deleteParamSubmit(obj) {
      //删除参数提交
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起删除请求
      this.$axios
        .delete("/categories/" + obj.cat_id + "/attributes/" + obj.attr_id)
        .then((res) => {
          if (res.meta.status == 200) {
            //提示成功信息
            this.$message.success(res.meta.msg);
            //重新刷新数据
            this.getCatParams(obj.attr_sel);
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    handleClose(obj, tag) {
      //删除动态参数标签
      this.catParams.forEach((item) => {
        if (item == obj) {
          item.attr_vals.splice(item.attr_vals.indexOf(tag), 1);
          //更新参数
          this.updateParams(obj);
        }
      });
    },
    showTagInput() {
      this.tagConfig.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.focus();
      });
    },
    handleInputConfirm(obj) {
      let inputValue = this.tagConfig.inputValue;
      if (inputValue) {
        //添加参数
        this.catParams.forEach((item) => {
          if (item == obj) {
            item.attr_vals.push(inputValue);
            //更新参数
            this.updateParams(obj);
          }
        });
      }
      this.tagConfig.inputVisible = false;
      this.tagConfig.inputValue = "";
    },
    updateParams(obj) {
      //更新参数
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .put("/categories/" + obj.cat_id + "/attributes/" + obj.attr_id, {
          attr_name: obj.attr_name,
          attr_sel: obj.attr_sel,
          attr_vals: obj.attr_vals.join(","),
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //提示成功信息
            this.$message.success(res.meta.msg);
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    selectCasNode() {
      //只允许为三级分类设置参数
      if (this.$refs["catCascader"].getCheckedNodes(true)[0]) {
        if (this.$refs["catCascader"].getCheckedNodes(true)[0].level !== 3) {
          console.log(this.$refs["catCascader"]);

          //禁用添加参数按钮
          this.addParamsBtnDisabled = true;
          //清空参数列表
          this.catParams = [];
          //重置级联选择器
          this.$refs["catCascader"].handleClear();
          //提示警告信息
          this.$message.warning("只允许为三级分类设置参数！");
        } else {
          //激活添加参数按钮
          this.addParamsBtnDisabled = false;
          //设置当前选中分类的ID
          this.selectCatId = this.$refs["catCascader"].getCheckedNodes(
            true
          )[0].data.cat_id;
          //获取参数数据
          this.getCatParams(this.addParamForm.type);
        }
      }
    },
    getCatParams(type) {
      //根据Id获取分类的参数列表
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .get("categories/" + this.selectCatId + "/attributes", {
          params: {
            sel: type,
          },
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //处理返回的数据
            res.data.forEach((item, index) => {
              //给每项数据添加索引
              item.index = index + 1;
              //将属性转换为数组形式
              item.attr_vals = item.attr_vals.split(",");
              if (item.attr_vals.length === 1 && item.attr_vals[0] == "") {
                item.attr_vals = [];
              }
            });

            //设置获取到的数据
            this.catParams = res.data;
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    addParam() {},
  },

  mounted() {
    //模板加载完成后渲染数据
    this.getCategoryList();
  },
};
</script>

<style lang="less" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>